<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Cache;
use think\facade\Event;
use addons\WeChatMini\facade\WeChatMini;

use app\common\controller\Config;

class User extends Base
{

    protected $name = 'user';

    protected $type = [
        'active_time' => 'timestamp',
    ];

    protected function role()
    {
        return $this->hasOne(UserRole::class, 'id', 'role_id')->field('id,title');
    }
    protected function level()
    {
        return $this->hasOne(Level::class, 'id', 'level_id')->field('id,title,sub_title');
    }

    public function assets()
    {
        return $this->hasOne(Assets::class, 'uid');
    }

    public function getNicknameAttr($value)
    {
        return $value ?: Cache::get('system')['default_nickname'];
    }

    public function getPhotoAttr($value)
    {
        return $value ?: Cache::get('system')['default_photo'];
    }

    protected function getMinTeamAttr($value, $data)
    {
        return self::geMinTeam($data['id']);
    }

    public static function _save($param, $logs)
    {
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $original = self::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    return ['code' => -1, 'msg' => '记录不存在，请检查！'];
                }
                $logs['original'] = $original;
                $model = self::update($param);
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
                $count = parent::where(['code' => $param['code']])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '会员编号已被注册'];
                }
                $count = parent::where(['mobile' => $param['mobile']])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '手机号已被注册'];
                }
                $parent = parent::where(['code' => $param['parent_code'], 'is_active' => 2])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                }
                $param['code'] = trim($param['code']);
                $param['mobile'] = trim($param['mobile']);
                $param['parent_id'] = $parent->id;
                $param['parent_name'] = $parent->nickname;
                $param['password'] = !empty($param['password']) ? md5($param['password']) : md5('111111');
                $param['pay_password'] = !empty($param['pay_password']) ? md5($param['pay_password']) : md5('222222');
                parent::create($param);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功', 'url' => url('login/index')->build()];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    //微信小程序手机号授权登录
    public static function _miniAppletSave($param)
    {
        try {
            if (!isset($param['openid'])) {
                return ['code' => -1, 'msg' => '无效code'];
            }
            $info = parent::where('openid', $param['openid'])->find();
            $token = md5(json_encode($param) . $param['mobile'] . time());
            if ($info) {
                if (empty($info->openid)) {
                    $info->openid = $param['openid'];
                }
                if (empty($info->mobile)) {
                    $info->mobile = $param['mobile'];
                }
                $info->last_time = time();
                $info->last_ip = request()->ip();
                $info->token = $token;
                $info->save();
            } else {
                if ($param['parent_code'] && isset($param['parent_code'])) {
                    $parent_code = $param['parent_code'];
                } else {
                    $parent_code = 'admin';
                }
                $parent = parent::where(['code' => $parent_code, 'is_active' => 2])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                }
                $code = generate(6, '', 1);
                $update['nickname'] = '匿名用户（' . $code . '）';
                $update['photo'] = '/static/admin/images/default.png';
                $update['openid'] = $param['openid'];
                $update['mobile'] = $param['mobile'];
                $update['last_time'] = time();
                $update['last_ip'] = request()->ip();
                $update['parent_id'] = $parent->id;
                $update['parent_code'] = $parent_code;
                $update['parent_name'] = $parent->nickname;
                $update['password'] =  md5('111111');
                $update['pay_password'] =  md5('222222');
                $update['token'] = $token;
                $update['code'] = $code;
                $update['is_active'] = 2;
                $update['active_time'] = time();
                $info=parent::create($update);
                self::giveMoney(Config::lists()['give_money'], $info->id);
            }
            return ['code' => 1, 'msg' => '登录成功', 'result' => ['token' => $token]];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 普通授权登录
     */

    public static function _miniLogin($param)
    {
        try {
            if (!isset($param['openid'])) {
                return ['code' => -1, 'msg' => '无效code'];
            }
            $info = parent::where('openid', $param['openid'])->find();
            $token = md5(json_encode($param) . $param['openid'] . time());
            if ($info) {
                if (empty($info->openid)) {
                    $info->openid = $param['openid'];
                }
                $info->last_time = time();
                $info->last_ip = request()->ip();
                $info->token = $token;
                $info->save();
            } else {
                if ($param['parent_code'] && isset($param['parent_code'])) {
                    $parent_code = $param['parent_code'];
                } else {
                    $parent_code = 'admin';
                }
                $parent = parent::where(['code' => $parent_code, 'is_active' => 2])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                }
                $code = generate(6, '', 1);
                $update['nickname'] = '匿名用户（' . $code . '）';
                $update['photo'] = '/static/admin/images/default.png';
                $update['openid'] = $param['openid'];
                $update['last_time'] = time();
                $update['last_ip'] = request()->ip();
                $update['parent_id'] = $parent->id;
                $update['parent_code'] = $parent_code;
                $update['parent_name'] = $parent->nickname;
                $update['password'] =  md5('111111');
                $update['pay_password'] =  md5('222222');
                $update['token'] = $token;
                $update['code'] = $code;
                $update['is_active'] = 2;
                $update['active_time'] = time();
                $info=parent::create($update);
                self::giveMoney(Config::lists()['give_money'], $info->id);
            }
            return ['code' => 1, 'msg' => '登录成功', 'result' => ['token' => $token]];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    public static function giveMoney($give_money, $uid)
    {
        try {
            Target::Account()->basics($uid, 'integral', $give_money, '新用户注册', '+')
                ->createNormal();
            return ['code' => 1, 'msg' => '赠送成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /***
     * 获取二维码
     */
    public static function getShare($user)
    {
        try {
            $system = Config::lists();
            if (!empty($user['qrurl'])) {
                $pdf_path = $_SERVER['DOCUMENT_ROOT'] . $user['qrurl'];
                if (file_exists($pdf_path)) {
                    unlink('.' . $user['qrurl']);
                }
            }
            $res = WeChatMini::getMiniScene($user->code, 'pages/index/index', '/qrcode', $system['env_version']);
            $user->qrurl = $res;
            $user->save();
            $data['url'] = $res;
            $data['code'] = $user->code;
            $data['title'] = '扫一扫，成为 '.$system['web_site_title'].' 会员';
            return ['code' => 1, 'msg' => '获取成功', 'data' => $data];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    public static function onAfterInsert($model)
    {
        if ($model->parent_code) {
            Relation::generate($model->id, $model->code, $model->parent_id, $model->parent_code);
        }
        $model->assets()->save(['uid' => $model->id]);

        Event::trigger('Statistics', ['key' => 'user', 'value' => 1]);
    }


    public static function recharge($param, $admin)
    {
        parent::startTrans();
        try {
            $user = parent::find($param['id']);
            if ($user->isEmpty()) {
                return json(['code' => -1, 'msg' => '未查询到相关会员']);
            }
            $account = get_pay_way($param['account']);
            if ($param['mode'] == 1) {
                Target::Account()
                    ->basics($param['id'], $param['account'], $param['amount'], '后台充值', '+')
                    ->setMsg($param['remarks'])
                    ->setQueueName('account_queue')
                    ->setOperator($admin->admin_name)
                    ->createRecharge();
                $logs = '后台充值【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            } else {
                Target::Account()
                    ->basics($param['id'], $param['account'], $param['amount'], '后台扣除', '-')
                    ->setMsg($param['remarks'])
                    ->setOperator($admin->admin_name)
                    ->createRecharge();
                $logs = '后台扣除【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            }

            Logs::adds($logs, $admin['id'], $admin['admin_name']);

            parent::commit();
            return json(['code' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            parent::rollback();
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }


    /**
     * 检测用户收款方式
     * @param $user
     */
    public static function checkReceipt($user)
    {
        // 微信
        if (
            empty($user->wechat_name) && empty($user->wechat_image)
            && empty($user->alipay_name) && empty($user->alipay_image)
            && empty($user->bank_name) && empty($user->bank_number)
        ) {
            return false;
        }
        return true;
    }

    /**
     * @param $uid
     * @return float|int
     * 原点 2021年12月28日11:50:17 计算小区业绩
     */
    public static function geMinTeam($uid)
    {
        $areaData = parent::where('parent_id', $uid)->order('team_total', 'desc')->column('my_total+team_total as team_total');
        if ($areaData) {
            array_shift($areaData);
            if (!empty($areaData)) return array_sum($areaData);
        }
        return 0;
    }
}
